<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="profile-page">
    <div class="page-container">
      <!-- 用户信息卡片 -->
      <div class="profile-card">
        <div class="profile-header">
          <div class="avatar-section">
            <el-avatar :size="80" :src="userStore.userAvatar" @error="handleAvatarLoadError">
              <el-icon><User /></el-icon>
            </el-avatar>
            <div class="upload-overlay" @click="showAvatarUpload = true">
              <el-icon><Camera /></el-icon>
            </div>
          </div>
          
          <div class="user-info">
            <h2>{{ userStore.userName || '未设置昵称' }}</h2>
            <div class="user-meta">
              <div class="meta-item">
                <el-icon><Calendar /></el-icon>
                <span>加入时间: {{ formatDate(userInfo?.createTime) }}</span>
              </div>
              <div class="meta-item" v-if="userInfo?.lastLoginTime">
                <el-icon><Clock /></el-icon>
                <span>最后登录: {{ formatDate(userInfo.lastLoginTime) }}</span>
              </div>
            </div>
          </div>

          <div class="profile-actions">
            <el-button type="primary" @click="$router.push('/profile/edit')" :icon="Edit">
              编辑资料
            </el-button>
          </div>
        </div>

        <!-- 统计数据 -->
        <div class="stats-section">
          <div class="stats-grid">
            <div class="stat-card" @click="$router.push('/study-records')">
              <div class="stat-icon learning">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ studyStats.totalTutorials || 0 }}</div>
                <div class="stat-label">学习教程</div>
              </div>
            </div>
            
            <div class="stat-card" @click="$router.push('/favorites')">
              <div class="stat-icon favorite">
                <el-icon><Collection /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ favoriteStats.totalCount || 0 }}</div>
                <div class="stat-label">收藏内容</div>
              </div>
            </div>


          </div>
        </div>
      </div>


      <!-- 我的收藏 -->
      <div class="favorite-section">
        <div class="section-header">
          <h3><el-icon><Collection /></el-icon> 我的收藏</h3>
          <router-link to="/favorites" class="more-link">
            查看全部 <el-icon><ArrowRight /></el-icon>
          </router-link>
        </div>

        <div class="favorite-content" v-loading="favoriteLoading">
          <div class="no-data" v-if="recentFavorites.length === 0">
            <el-empty description="暂无收藏内容">
              <el-button type="primary" @click="$router.push('/culture')">
                浏览内容
              </el-button>
            </el-empty>
          </div>

          <div class="favorite-tabs" v-else>
            <el-tabs v-model="favoriteActiveTab">
              <el-tab-pane label="文化" name="culture">
                <div class="favorite-grid">
                  <div
                    v-for="item in cultureFavorites"
                    :key="item.id"
                    class="favorite-card"
                    @click="$router.push(`/culture/${item.targetId}`)"
                  >
                    <div class="card-image">
                      <img :src="item.content?.coverImage || '/default-culture.jpg'" :alt="item.content?.title" />
                    </div>
                    <div class="card-content">
                      <h5>{{ item.content?.title }}</h5>
                      <p>{{ item.content?.summary }}</p>
                    </div>
                  </div>
                </div>
              </el-tab-pane>

              <el-tab-pane label="教程" name="tutorial">
                <div class="favorite-grid">
                  <div
                    v-for="item in tutorialFavorites"
                    :key="item.id"
                    class="favorite-card"
                    @click="$router.push(`/tutorial/${item.targetId}`)"
                  >
                    <div class="card-image">
                      <img :src="item.content?.coverImage || '/default-tutorial.jpg'" :alt="item.content?.title" />
                    </div>
                    <div class="card-content">
                      <h5>{{ item.content?.title }}</h5>
                      <p>{{ item.content?.summary }}</p>
                    </div>
                  </div>
                </div>
              </el-tab-pane>

              <el-tab-pane label="资讯" name="news">
                <div class="favorite-grid">
                  <div
                    v-for="item in newsFavorites"
                    :key="item.id"
                    class="favorite-card"
                    @click="$router.push(`/news/${item.targetId}`)"
                  >
                    <div class="card-image">
                      <img :src="item.content?.coverImage || '/default-news.jpg'" :alt="item.content?.title" />
                    </div>
                    <div class="card-content">
                      <h5>{{ item.content?.title }}</h5>
                      <p>{{ item.content?.summary }}</p>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
    </div>

    <!-- 头像上传对话框 -->
    <el-dialog v-model="showAvatarUpload" title="更换头像" width="400px">
      <div class="avatar-upload">
        <el-upload
          ref="uploadRef"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError"
          :headers="uploadHeaders"
          action="/api/upload/avatar"
          accept="image/*"
          name="file"
        >
          <div class="upload-area">
            <el-icon><Plus /></el-icon>
            <div class="upload-text">点击上传头像</div>
          </div>
        </el-upload>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  User, Camera, Calendar, Clock, Edit, Document, Collection,
  ArrowRight, Check, Plus
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { userFavoriteApi, userStudyApi } from '@/api'
import type { UserFavorite } from '@/types/common'
import { getToken } from '@/utils/request'

const router = useRouter()
const userStore = useUserStore()

// 上传配置
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${getToken()}`
}))

// 响应式数据
const userInfo = computed(() => userStore.userInfo)
const favoriteLoading = ref(false)
const showAvatarUpload = ref(false)
const favoriteActiveTab = ref('culture')

const studyStats = reactive({
  totalTutorials: 0
})

const favoriteStats = reactive({
  totalCount: 0,
  cultureCount: 0,
  tutorialCount: 0,
  newsCount: 0
})

const recentFavorites = ref<UserFavorite[]>([])

// 计算收藏分类
const cultureFavorites = computed(() => 
  recentFavorites.value.filter(item => item.targetType === 'culture')
)
const tutorialFavorites = computed(() => 
  recentFavorites.value.filter(item => item.targetType === 'tutorial')
)
const newsFavorites = computed(() => 
  recentFavorites.value.filter(item => item.targetType === 'news')
)

// 获取学习统计
const fetchStudyStats = async () => {
  try {
    console.log('获取学习统计...')
    const response = await userStudyApi.getStudyProgress()
    console.log('学习统计响应:', response.data)
    
    // 确保数据存在且格式正确
    if (response.data) {
      studyStats.totalTutorials = response.data.totalTutorials || 0
      console.log('学习统计已更新:', studyStats)
    } else {
      console.warn('学习统计数据为空')
      studyStats.totalTutorials = 0
    }
  } catch (error: any) {
    console.error('获取学习统计失败，详细错误:', {
      error,
      message: error?.message,
      response: error?.response,
      data: error?.response?.data
    })
    studyStats.totalTutorials = 0
  }
}


// 获取最近收藏
const fetchRecentFavorites = async () => {
  favoriteLoading.value = true
  try {
    const response = await userFavoriteApi.getFavoriteList()
    recentFavorites.value = response.data.slice(0, 18) // 每个分类最多6个

    // 统计收藏数量
    favoriteStats.totalCount = response.data.length
    favoriteStats.cultureCount = response.data.filter((item: UserFavorite) => item.targetType === 'culture').length
    favoriteStats.tutorialCount = response.data.filter((item: UserFavorite) => item.targetType === 'tutorial').length
    favoriteStats.newsCount = response.data.filter((item: UserFavorite) => item.targetType === 'news').length
  } catch (error) {
    console.error('获取收藏列表失败:', error)
  } finally {
    favoriteLoading.value = false
  }
}


// 头像上传处理
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarSuccess = (response: any) => {
  if (response.code === 200) {
    // 更新用户头像
    userStore.updateUserInfo({ avatarUrl: response.data.url })
    ElMessage.success('头像更新成功')
    showAvatarUpload.value = false
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

// 头像上传失败处理
const handleAvatarError = (error: any) => {
  console.error('头像上传失败:', error)
  ElMessage.error('头像上传失败，请重试')
}

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '--'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 头像图片加载错误处理
const handleAvatarLoadError = (e: Event) => {
  console.log('头像加载失败，使用默认头像')
  // Element Plus 的 Avatar 组件会自动显示 slot 内容（User 图标）
}

onMounted(() => {
  fetchStudyStats()
  fetchRecentFavorites()
})
</script>

<style scoped>
.profile-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 用户信息卡片 */
.profile-card {
  background: #fff;
  border-radius: 12px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.profile-header {
  background: linear-gradient(135deg, #8B0000 0%, #DC143C 100%);
  color: #fff;
  padding: 32px;
  display: flex;
  align-items: center;
  gap: 24px;
}

.avatar-section {
  position: relative;
  cursor: pointer;
}

.avatar-section:hover .upload-overlay {
  opacity: 1;
}

.upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.upload-overlay .el-icon {
  font-size: 24px;
  color: #fff;
}

.user-info {
  flex: 1;
}

.user-info h2 {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 12px;
}

.user-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  opacity: 0.9;
}

.profile-actions {
  display: flex;
  gap: 12px;
}

/* 统计数据 */
.stats-section {
  padding: 24px 32px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
  transition: all 0.3s;
  cursor: pointer;
}

.stat-card:hover {
  background: #f0f0f0;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #fff;
}

.stat-icon.learning {
  background: linear-gradient(135deg, #8B0000, #DC143C);
}

.stat-icon.favorite {
  background: linear-gradient(135deg, #B22222, #FF6B6B);
}



.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

/* 区块通用样式 */
.favorite-section {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.more-link {
  color: #DC143C;
  text-decoration: none;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
}

.more-link:hover {
  color: #8B0000;
  text-decoration: underline;
}

.no-data {
  text-align: center;
  padding: 40px 20px;
}


/* 我的收藏 */
.favorite-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.favorite-card {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  cursor: pointer;
}

.favorite-card:hover {
  border-color: #DC143C;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.favorite-card .card-image {
  height: 100px;
  overflow: hidden;
}

.favorite-card .card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.favorite-card:hover .card-image img {
  transform: scale(1.05);
}

.favorite-card .card-content {
  padding: 12px;
}

.favorite-card .card-content h5 {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.favorite-card .card-content p {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 头像上传 */
.avatar-upload {
  text-align: center;
}

.upload-area {
  width: 200px;
  height: 200px;
  border: 2px dashed #ddd;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-area:hover {
  border-color: #DC143C;
  background: #fff5f7;
}

.upload-area .el-icon {
  font-size: 48px;
  color: #999;
  margin-bottom: 12px;
}

.upload-text {
  color: #666;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 16px;
  }

  .profile-header {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }

  .profile-actions {
    justify-content: center;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }


  .favorite-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }

  .favorite-grid {
    grid-template-columns: 1fr;
  }
}
</style>
